<template>
  <div class="goods-class">
    <el-card class="mb-4">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="姓名">
          <el-input v-model="searchForm.nickname" placeholder="请输入姓名" clearable class="w-60" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable class="w-60" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select filterable  v-model="searchForm.shelf" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户类型">
          <el-select filterable  v-model="searchForm.type" placeholder="请选择用户类型">
            <el-option label="全部" value="" />
            <el-option label="用户" :value="1" />
            <el-option label="员工" :value="2" />
            <el-option label="商户" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-form-item label="品牌店铺" prop="shopId">
            <el-select filterable  v-model="searchForm.shopId" placeholder="请选择品牌店铺" class="w-full">
              <el-option :label="item.name" :value="item.id" v-for="item,index in merchantList" :key="index" />
            </el-select>
          </el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <!-- <el-button type="primary" @click="handleAdd" v-has="'coupon:save'"
                                                            style="margin-left: 30px">新增优惠券</el-button> -->
        </el-form-item>
      </el-form>
    </el-card>
  
    <!-- 表格 -->
    <el-table v-loading="loading" :data="tableData" border style="width: 100%;margin-top:15px">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="userNo" label="会员编号" />
      <el-table-column prop="nickname" label="昵称" />
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="credit" label="积分" />
      <el-table-column prop="cardNo" label="员工卡" />
      <el-table-column prop="type" label="用户类型" width="100">
        <template #default="{ row }">
          <el-tag>{{ row.type === 1 ? '用户' : row.type === 2 ? '员工' : '商管' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="是否为商管" width="120">
        <template #default="{ row }">
          <el-tag v-if="row.type === 3" type="success">是</el-tag>
          <el-tag v-else type="info">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="position" label="职位" />
      <el-table-column prop="area" label="头像" width="150" align="center">
        <template slot-scope="scope">
          <img :src="scope.row.avatar || 'https://img.shihhl.com/shequ/mr.png'" style="width: 90px;height: 90px" alt="">
        </template>
      </el-table-column>
      <el-table-column prop="couponCount" label="优惠券数量" width="100" />
      <!-- <el-table-column prop="createTime" label="创建时间" width="180" /> -->
      <el-table-column label="操作" fixed="right" width="160">
        <template #default="{ row }">
          <el-button type="text" v-has="'user:update'" @click="handleEdit(row)">编辑</el-button>
          <el-button type="text" v-has="'user:update'" @click="switchUserTypeChnage(row)"
            v-if="row.type === 2 || row.type === 3">{{row.type === 2 ? '成为商管' : '成为员工' }}</el-button>
          <el-button type="text" v-has="'user:update'" @click="handleUnbind(row)" v-if="row.type === 2">解绑</el-button>
          <el-button type="text" style="color: #f56c6c" @click="handleDelete(row)" v-has="'user:status'">{{
            row.status == 1 ? '禁用' : '启用' }}</el-button>
        </template>
      </el-table-column>
    </el-table>
  
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next" :total="total">
      </el-pagination>
    </div>
  
    <!-- 新增/编辑弹窗 -->
    <el-dialog :close-on-click-modal="false"  :title="dialogType === 'add' ? '新增' : '编辑'" :visible.sync="dialogVisible" width="80%" @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户类型" prop="type">
          <el-select filterable  v-model="form.type" placeholder="请选择用户类型" style="width: 100%">
            <el-option label="用户" :value="1" />
            <el-option label="员工" :value="2" />
            <!-- <el-option label="商户" :value="3" /> -->
          </el-select>
        </el-form-item>
        <el-form-item label="商铺" prop="shopId" v-if="form.type === 2">
          <el-select filterable  v-model="form.shopId" placeholder="请选择商铺" style="width: 100%">
            <el-option :label="item.name" :value="item.id" v-for="item,index in merchantList" :key="index" />
          </el-select>
        </el-form-item>
        <el-form-item label="职位" prop="position" v-if="form.type === 2">
          <el-input v-model="form.position" placeholder="请输入职位" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
  
  <script>
export default {
  name: 'userList',
  data() {
    return {
      // 搜索表单
      searchForm: {
        nickname: '',
        phone: '',
        shelf: '',
        type: '',
        shopId: '',
      },
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 表格数据
      tableData: [],
      total: 10,
      loading: false,
      // 弹窗相关
      dialogVisible: false,
      dialogType: 'add', // add 或 edit
      form: {
        type: '',
        position: '',
        shopId: '',
      },
      // 表单校验规则
      rules: {
        type: [
          { required: true, message: '请选择用户类型', trigger: 'blur' },
        ],
        position: [
          { required: true, message: '请输入职位', trigger: 'blur' },
        ],
        shopId: [
          { required: true, message: '请选择商铺', trigger: 'blur' },
        ],
      },
      merchantList: []
    }
  },
  created() {
    this.getList()
    this.getMerchantList()
  },
  methods: {
    switchUserTypeChnage(row) {
      this.$confirm('确定要切换吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        await this.$api.switchUserType(row.id, row.type === 2 ? 3 : 2)
        this.$message.success('切换成功')
        this.getList()
      })
    },
    handleUnbind(row) {
      this.$confirm('确定要解绑吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        await this.$api.unbindUser(row.id)
        this.$message.success('解绑成功')
        this.getList()
      })
    },
    async getMerchantList() {
      const { data } = await this.$api.shopPageList({
        page: 1,
        size: 10000,
        condition: {
          categoryId: '',
          areaId: '',
          floorId: '',
        }
      })
      console.log(data, '111111');
      this.merchantList = data.result.records
    },
    // 获取列表数据
    async getList() {
      this.loading = true
      try {
        const { data } = await this.$api.getUserLists({
          page: this.currentPage,
          size: this.pageSize,
          condition: {
            ...this.searchForm
          }
        })
        console.log(data, 'data');
        this.tableData = data.result.records
        this.total = data.result.total
      } catch (error) {
        console.error('获取商品分类列表失败：', error)
      } finally {
        this.loading = false
      }
    },
    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.getList()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        nickname: '',
        phone: '',
        shelf: '',
        type: '',
        shopId: '',
      }
      this.handleSearch()
    },
    // 分页相关
    handleSizeChange(val) {
      this.pageSize = val
      this.getList()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },
    // 新增
    handleAdd() {
      console.log('新增');
      this.dialogType = 'add'
      this.dialogVisible = true
    },
    // 编辑
    handleEdit(row) {
      this.dialogType = 'edit'
      this.form = { ...row }
      this.dialogVisible = true
    },
    // 修改
    handleDelete(row) {
      this.$confirm('确定要修改状态吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await this.$api.userStatus({ id: row.id, status: row.status == 1 ? 0 : 1 })
          this.$message.success('操作成功')
          this.getList()
        } catch (error) {
          console.error('删除失败：', error)
        }
      }).catch(() => { })
    },
    // 提交表单
    handleSubmit() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            if (this.dialogType === 'add') {
              // await this.$api.addUser({
              //   name: this.form.name,
              // })
              // this.$message.success('新增成功')
            } else {
              await this.$api.updateUserType({
                type: this.form.type,
                id: this.form.id,
                position: this.form.position,
                shopId: this.form.shopId
              })
              this.$message.success('编辑成功')
            }
            this.dialogVisible = false
            this.getList()
          } catch (error) {
            console.error('保存失败：', error)
          }
        }
      })
    },
    // 重置表单
    resetForm() {
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields()
      }
      this.form = {
        name: '',
        sort: 0
      }
    }
  }
}
  </script>
  
  <style lang="scss" scoped>
.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .goods-class {
    padding: 20px;
  }
</style>